import createMatcher from './create-matcher';
import HashHistory from './history/hash';
import BrowserHistory from './history/history';
import {install, _Vue} from './install';
console.log ('_Vue=========', _Vue);

class VueRouter {
  constructor (options) {
    // 根据用户的 routes 配置生成一个映射表，后面跳转路由时，根据路径找到对应的组件来渲染
    this.matcher = createMatcher (options.routes || []);

    this.beforeEachHooks = [];
    // console.log ('this.matcher----------', this.matcher);

    // 根据 mode 创建两种不同的路由策略
    switch (options.mode) {
      case 'hash':
        this.history = new HashHistory (this);
        break;
      case 'history':
        this.history = new BrowserHistory (this);
        break;
    }
  }

  // 根据当前路径找到匹配记录
  match (location) {
    return this.matcher.match (location);
  }
  // 路由初始化,需要跳转一次并且开启监听，在监听中进行后续跳转
  init (app) {
    const history = this.history; // 可能是 hash 也可能是 browser
    const setupHashListener = () => {
      history.setupListener (); // hash 和 browser 都有各自监听 path 变化的方法
    };
    let location = history.getCurrentLocation ();
    history.transitionTo (location, setupHashListener); // 跳转到对应组件，最核心 API

    // 监听当前路由，当其改变时, 更新根实例的 _route 值
    history.listen (route => {
      app._route = route;
    });
    console.log ('init =========');
  }

  push (location) {
    this.history.push (location);
  }
  beforeEach (fn) {
    this.beforeEachHooks.push (fn);
  }
}

// Vue.use(VueRouter)  ,VueRouter 需要有一个 install 方法
VueRouter.install = install;

export default VueRouter;
